from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from loguru import logger
import sys

from app.api.routes import router
from app.api.asr_routes import router as asr_router
from app.api.config_routes import router as config_router
from app.utils.database import db_manager
from config import config

# 配置日志
logger.remove()
logger.add(
    sys.stdout,
    level=config.LOGGING["level"],
    format="<green>{time:YYYY-MM-DD HH:mm:ss}</green> | <level>{level: <8}</level> | <cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan> - <level>{message}</level>"
)
logger.add(
    config.LOGGING["file"],
    level=config.LOGGING["level"],
    format="{time:YYYY-MM-DD HH:mm:ss} | {level: <8} | {name}:{function}:{line} - {message}",
    rotation="10 MB",
    retention="7 days"
)

# 创建FastAPI应用
app = FastAPI(
    title="AI视频翻译平台",
    description="基于AI技术的视频自动翻译平台，支持多语言翻译、语音合成和唇形同步",
    version="1.0.0",
    docs_url="/docs",
    redoc_url="/redoc",
    swagger_ui_parameters={
        "defaultModelsExpandDepth": -1,
        "defaultModelExpandDepth": 1,
        "displayRequestDuration": True,
        "docExpansion": "list",
        "filter": True,
        "showExtensions": True,
        "showCommonExtensions": True,
        "tryItOutEnabled": True,
        "syntaxHighlight.theme": "monokai"
    }
)

# 配置CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 生产环境中应该设置具体的域名
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 注册路由
app.include_router(router)
app.include_router(asr_router)
app.include_router(config_router)

@app.on_event("startup")
async def startup_event():
    """应用启动时的初始化"""
    logger.info("正在启动AI视频翻译平台...")
    
    try:
        # 初始化数据库
        db_manager.create_tables()
        logger.info("数据库初始化完成")
        
        logger.info("AI视频翻译平台启动成功")
        
    except Exception as e:
        logger.error(f"应用启动失败: {e}")
        raise

@app.on_event("shutdown")
async def shutdown_event():
    """应用关闭时的清理"""
    logger.info("正在关闭AI视频翻译平台...")

@app.get("/")
async def root():
    """根路径"""
    return {
        "message": "欢迎使用AI视频翻译平台",
        "version": "1.0.0",
        "docs": "/docs",
        "health": "/api/v1/health"
    }

if __name__ == "__main__":
    import uvicorn
    
    logger.info(f"启动服务器: http://0.0.0.0:8000")
    uvicorn.run(
        "main:app",
        host="0.0.0.0",
        port=8000,
        reload=True,
        log_level=config.LOGGING["level"].lower()
    ) 